package com.md.application.service;

import com.md.api.LoginApi;
import com.md.base.exception.ServerException;
import com.md.domain.service.LoginDomainService;
import com.md.model.system.CommonResult;
import com.md.request.AzureSamlLoginRequest;
import com.md.request.LoginRequest;
import com.md.response.LoginResponse;
import com.md.response.UsersResponse;
import com.md.value.enums.ErrorEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;

@Service
@AllArgsConstructor
public class LoginService implements LoginApi {
  private final LoginDomainService loginDomainService;

  static byte[] samlDeflate(final String s) {
    try {
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true));
      deflater.write(s.getBytes(StandardCharsets.UTF_8));
      deflater.finish();
      return b.toByteArray();
    } catch (IOException ex) {
      throw ServerException.build(ErrorEnum.DECODING_ERROR, ex);
    }
  }

  @Override
  public CommonResult<Void> azureSaml(final AzureSamlLoginRequest request) {
    return null;
  }

  @Override
  public CommonResult<LoginResponse> login(final LoginRequest request) {

    UsersResponse response = null;
    switch (request.getType()) {
      case PHONE_CODE:
        response = loginDomainService.loginPhoneCode(request.getPhone(), request.getCode());
        break;
      case ACCOUNT_PASSWORD:
        response = loginDomainService.loginAccountPassword(request.getAccount(), request.getPassword());
        break;
      case PHONE_PASSWORD:
        response = loginDomainService.loginPhonePassword(request.getPhone(), request.getPassword());
        break;
      default:
        break;
    }
    return CommonResult.success(response);

    return null;
  }

  private void addParameter(final String name, final String value, final UriComponentsBuilder builder) {
    if (StringUtils.hasText(value)) {
      builder.queryParam(UriUtils.encode(name, StandardCharsets.ISO_8859_1),
        UriUtils.encode(value, StandardCharsets.ISO_8859_1));
    }
  }
}
